package com.coursehub.user.controller;

import com.coursehub.shared.dto.ApiResponse;
import com.coursehub.user.dto.LoginResponseDto;
import com.coursehub.user.dto.UserLoginDto;
import com.coursehub.user.dto.UserRegisterDto;
import com.coursehub.user.dto.UserUpdateDto;
import com.coursehub.user.entity.User;
import com.coursehub.user.service.UserService;
import com.coursehub.user.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 用户管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<User>> registerUser(@Valid @RequestBody UserRegisterDto registerDto) {
        log.info("用户注册请求: {}", registerDto.getUserAccount());
        User registeredUser = userService.registerUser(registerDto);
        return ResponseEntity.ok(ApiResponse.success("注册成功", registeredUser));
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<LoginResponseDto>> login(@Valid @RequestBody UserLoginDto loginDto) {
        log.info("用户登录请求: {}", loginDto.getUserAccount());
        User user = userService.login(loginDto);
        
        // 生成JWT token
        String token = jwtUtil.generateToken(user.getUserId(), user.getUserAccount(), user.getUserName());
        LoginResponseDto loginResponse = new LoginResponseDto(token, user);
        
        return ResponseEntity.ok(ApiResponse.success("登录成功", loginResponse));
    }

    /**
     * 用户登录（兼容原有接口）
     */
    @PostMapping("/login/legacy")
    public ResponseEntity<ApiResponse<LoginResponseDto>> loginLegacy(
            @RequestParam String account, 
            @RequestParam String password) {
        log.info("用户登录请求（兼容接口）: {}", account);
        User user = userService.login(account, password);
        
        // 生成JWT token
        String token = jwtUtil.generateToken(user.getUserId(), user.getUserAccount(), user.getUserName());
        LoginResponseDto loginResponse = new LoginResponseDto(token, user);
        
        return ResponseEntity.ok(ApiResponse.success("登录成功", loginResponse));
    }

    /**
     * 用户注销
     */
    @PostMapping("/logout")
    public ResponseEntity<ApiResponse<Void>> logout() {
        userService.logout();
        return ResponseEntity.ok(ApiResponse.success("注销成功"));
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/{userId}")
    public ResponseEntity<ApiResponse<User>> updateUser(
            @PathVariable String userId,
            @Valid @RequestBody UserUpdateDto updateDto) {
        log.info("更新用户信息请求: {}", userId);
        User updatedUser = userService.updateUserInfo(userId, updateDto);
        return ResponseEntity.ok(ApiResponse.success("更新成功", updatedUser));
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{userId}")
    public ResponseEntity<ApiResponse<Void>> deleteUser(@PathVariable String userId) {
        log.info("删除用户请求: {}", userId);
        userService.deleteUser(userId);
        return ResponseEntity.ok(ApiResponse.success("删除成功"));
    }

    /**
     * 根据ID获取用户
     */
    @GetMapping("/{userId}")
    public ResponseEntity<ApiResponse<User>> getUserById(@PathVariable String userId) {
        User user = userService.getUserById(userId);
        return ResponseEntity.ok(ApiResponse.success(user));
    }

    /**
     * 获取所有用户
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<User>>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return ResponseEntity.ok(ApiResponse.success(users));
    }

    /**
     * 检查用户是否存在
     */
    @GetMapping("/{userId}/exists")
    public ResponseEntity<ApiResponse<Boolean>> userExists(@PathVariable String userId) {
        boolean exists = userService.userExists(userId);
        return ResponseEntity.ok(ApiResponse.success(exists));
    }

    /**
     * 根据账号检查用户是否存在
     */
    @GetMapping("/account/{userAccount}/exists")
    public ResponseEntity<ApiResponse<Boolean>> userExistsByAccount(@PathVariable String userAccount) {
        boolean exists = userService.userExistsByAccount(userAccount);
        return ResponseEntity.ok(ApiResponse.success(exists));
    }

    /**
     * 验证用户密码
     */
    @PostMapping("/{userId}/verify-password")
    public ResponseEntity<ApiResponse<Boolean>> verifyPassword(
            @PathVariable String userId,
            @RequestParam String password) {
        boolean valid = userService.checkUserPassword(userId, password);
        return ResponseEntity.ok(ApiResponse.success(valid));
    }
}